package test

import org.gradle.testkit.runner.TaskOutcome
import org.junit.Assert
import org.junit.Test
import util.TestUtils
import util.TestUtils.withTestProject


class LazyTests {
  @Test
  fun `properties are not called during configuration`() {

    val apolloConfiguration = """
apollo {
  service("service") {
    packageNamesFromFilePaths()
    useSemanticNaming.set(project.provider {
        throw IllegalArgumentException("this should not be called during configuration")
    })
  }
}
    """.trimIndent()
    TestUtils.withProject(
        usesKotlinDsl = true,
        plugins = listOf(TestUtils.kotlinJvmPlugin, TestUtils.apolloPlugin),
        apolloConfiguration = apolloConfiguration
    ) { dir ->
      TestUtils.executeGradle(dir, "tasks", "--all")
    }
  }


  @Test
  fun `graphql files can be generated by another task`() {

    val apolloConfiguration = """
abstract class InstallGraphQLFilesTask: DefaultTask() {
  @get:InputDirectory
  abstract val inputDir: DirectoryProperty

  @get:OutputDirectory
  abstract val outputDir: DirectoryProperty

  @TaskAction
  fun taskAction() {
    println("installing graphql files")
    inputDir.asFile.get().copyRecursively(outputDir.asFile.get())
  }
}
val installTask = tasks.register("installTask", InstallGraphQLFilesTask::class.java) {
  outputDir.set(project.file("build/toto"))
  inputDir.set(project.file("src/main/graphql/com/example"))
}
apollo {
  service("service") {
    packageNamesFromFilePaths()
    srcDir(installTask.flatMap { it.outputDir })
  }
}
""".trimIndent()

    TestUtils.withProject(
        usesKotlinDsl = true,
        plugins = listOf(TestUtils.kotlinJvmPlugin, TestUtils.apolloPlugin),
        apolloConfiguration = apolloConfiguration
    ) { dir ->
      val result = TestUtils.executeTask("generateApolloSources", dir)
      Assert.assertEquals(TaskOutcome.SUCCESS, result.task(":generateApolloSources")!!.outcome)
      Assert.assertEquals(TaskOutcome.SUCCESS, result.task(":installTask")?.outcome)
    }
  }

  @Test
  fun `schema file can be generated by another task`() {
    withTestProject("lazy-schema-file") { dir ->
      val result = TestUtils.executeTask("generateApolloSources", dir)
      Assert.assertEquals(TaskOutcome.SUCCESS, result.task(":generateApolloSources")!!.outcome)
      Assert.assertEquals(TaskOutcome.SUCCESS, result.task(":generateSchema")?.outcome)
    }
  }
}
